<template>
  <BasicModal v-bind="config" @register="registerModal" :title="currTitle"
              wrapClassName="loginSelectModal" v-model:visible="visible">
    <a-form ref="formRef" :model="formState" :rules="rules" v-bind="layout" :colon="false"
            class="loginSelectForm">
      <!--多商户选择-->
      <a-form-item v-if="isMultiBusiness" :validate-status="validate_status1" :colon="false">
        <!--label内容-->
        <template #label>
          <a-tooltip placement="topLeft">
            <template #title>
              <span>您隶属于多商户，请选择登录商户</span>
            </template>
            <a-avatar style="background-color: rgb(104, 208, 203)" :size="30"> 商户</a-avatar>
          </a-tooltip>
        </template>
        <template #extra v-if="validate_status1 == 'error'">
          <span style="color: #ed6f6f">请选择登录商户</span>
        </template>
        <!--商户下拉内容-->
        <a-select
          v-model:value="formState.curBusiness"
          @change="handleBusinessChange"
          placeholder="请选择登录商户"
          :class="{ 'valid-error': validate_status1 == 'error' }"
        >
          <template v-for="business in businessList" :key="business.businessId">
            <a-select-option :value="business.businessId">{{ business.businessName }}
            </a-select-option>
          </template>
        </a-select>
      </a-form-item>
      <!--多公司选择-->
      <a-form-item v-if="isMultiCompany" :validate-status="validate_status" :colon="false">
        <!--label内容-->
        <template #label>
          <a-tooltip placement="topLeft">
            <template #title>
              <span>您隶属于多公司，请选择登录公司</span>
            </template>
            <a-avatar style="background-color: #87d068" :size="30"> 公司</a-avatar>
          </a-tooltip>
        </template>
        <template #extra v-if="validate_status == 'error'">
          <span style="color: #ed6f6f">请选择登录公司</span>
        </template>
        <!--公司下拉内容-->
        <a-select
          v-model:value="formState.curCompany"
          @change="handleCompanyChange"
          placeholder="请选择登录公司"
          :class="{ 'valid-error': validate_status == 'error' }"
        >
          <template v-for="company in companyList" :key="company.companyId">
            <a-select-option :value="company.companyId">{{ company.companyName }}</a-select-option>
          </template>
        </a-select>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button @click="handleSubmit" type="primary">确认</a-button>
    </template>
  </BasicModal>
</template>

<script lang="ts">
import { defineComponent, ref, computed, watch, unref, reactive, UnwrapRef } from "vue";
import { Avatar } from "ant-design-vue";
import { BasicModal, useModalInner } from "/@/components/Modal";
import { useMessage } from "/@/hooks/web/useMessage";
import { useUserStore } from "/@/store/modules/user";
import { defHttp } from "/@/utils/http/axios";
import { getCurrentUserBusiness, getCurrentUserCompany } from "/@/views/system/user/user.api";

interface FormState {
  curBusiness: string | undefined;
  curCompany: string | undefined;
}

export default defineComponent({
  name: "loginSelect",
  components: {
    Avatar,
    BasicModal
  },
  emits: ["success", "register"],
  setup(props, { emit }) {
    const userStore = useUserStore();
    const { notification } = useMessage();
    //公司配置
    const isMultiCompany = ref(false);
    const companyList = ref([]);
    const validate_status = ref("");
    //商户配置
    const isMultiBusiness = ref(false);
    const businessList = ref([]);
    const validate_status1 = ref("");
    //弹窗显隐
    const visible = ref(false);
    //登录用户
    const username = ref("");
    //表单
    const formRef = ref();
    //选择的公司商户信息
    const formState: UnwrapRef<FormState> = reactive({
      curBusiness: undefined,
      curCompany: undefined,
    });

    const config = {
      maskClosable: false,
      closable: false,
      canFullscreen: false,
      width: "500px",
      minHeight: 20,
      maxHeight: 20
    };
    //弹窗操作
    const [registerModal, { closeModal }] = useModalInner();

    //当前标题
    const currTitle = computed(() => {
      if (unref(isMultiBusiness) && unref(isMultiCompany)) {
        return "请选择登录商户和公司";
      } else if (unref(isMultiBusiness) && !unref(isMultiCompany)) {
        return "请选择登录商户";
      } else if (!unref(isMultiBusiness) && unref(isMultiCompany)) {
        return "请选择登录公司";
      }
    });

    const rules = ref({
      curBusiness: [{ required: unref(isMultiBusiness), message: "请选择商户", trigger: "change" }],
      curCompany: [{required: unref(isMultiCompany), message: "请选择公司", trigger: "change" }],
    });

    const layout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 18 }
    };

    /**
     * 处理商户情况
     */
    function bizBusiness(loginResult) {
      //console.log("~~~~~~loginResult~~~~~~~:",loginResult)
      let multi_business = loginResult.multi_business;
      //0:无商户，1:一个商户，2:多个商户
      if (multi_business == 0) {
        notification.warn({
          message: "提示",
          description: `您尚未归属商户，请确认账号信息`,
          duration: 3
        });
        isMultiBusiness.value = false;
      } else if (multi_business == 2) {
        isMultiBusiness.value = true;
        businessList.value = loginResult.businessList;
      } else {
        isMultiBusiness.value = false;
      }
    }

    /**
     * 处理公司情况
     */
    function bizCompanyList(loginResult) {
      let multi_company = loginResult.multi_company;
      //0:没有商户或一个商户无公司，1:一个商户一个公司，2:一个商户多个公司，3：多个商户多个公司
      if (multi_company == 0) {
        notification.warn({
          message: "提示",
          description: `您尚未归属公司，请确认账号信息`,
          duration: 3
        });
        isMultiCompany.value = false;
      } else if(multi_company == 1){
        isMultiCompany.value = false;
      } else if (multi_company == 2) {
        isMultiCompany.value = true;
        companyList.value = loginResult.companyList;
      } else if (multi_company == 3) {
        isMultiCompany.value = true;
      } else {
        isMultiCompany.value = false;
      }
    }

    /**
     * 确认选中的公司和商户信息
     */
    function handleSubmit() {
      if (unref(isMultiBusiness) && !formState.curBusiness) {
        validate_status1.value = "error";
        return false;
      }
      if (unref(isMultiCompany) && !formState.curCompany) {
        validate_status.value = "error";
        return false;
      }
      formRef.value
        .validate()
        .then(() => {
          //切换商户选择
          if (unref(isMultiBusiness)) {
            businessResolve()
              .then(() => {
                emit("success");
              })
              .catch((e) => {
                notification.warn({
                  message: "提示",
                  description: `登录选择出现问题`,
                  duration: 3
                });
              })
              .finally(() => {
                close();
              });
          }
          //切换公司选择
          if (unref(isMultiCompany)) {
            companyResolve()
              .then(() => {
                emit("success");
              })
              .catch((e) => {
                notification.warn({
                  message: "提示",
                  description: `登录选择出现问题`,
                  duration: 3
                });
              })
              .finally(() => {
                close();
              });
          }
        })
        .catch((err) => {
          console.log("表单校验未通过error", err);
        });
    }

    /**
     *切换选择商户
     */
    function businessResolve() {
      return new Promise<void>((resolve, reject) => {
        if (!unref(isMultiBusiness)) {
          resolve();
        } else {
          let params = { curBusiness: formState.curBusiness, username: unref(username) };
          defHttp.put({ url: "/sys/selectBusiness", params }).then((res) => {
            if (res.userInfo) {
              userStore.setUserInfo(res.userInfo);
              resolve();
            } else {
              requestFailed(res);
              userStore.logout();
              reject();
            }
          });
        }
      });
    }

    /**
     *切换选择公司
     */
    function companyResolve() {
      return new Promise<void>((resolve, reject) => {
        if (!unref(isMultiCompany)) {
          resolve();
        } else {
          let params = { curCompany: formState.curCompany, username: unref(username) };
          defHttp.put({ url: "/sys/selectCompany", params }).then((res) => {
            if (res.userInfo) {
              userStore.setUserInfo(res.userInfo);
              resolve();
            } else {
              requestFailed(res);
              userStore.logout();
              reject();
            }
          });
        }
      });
    }

    /**
     * 请求失败处理
     */
    function requestFailed(err) {
      notification.error({
        message: "登录失败",
        description: ((err.response || {}).data || {}).message || err.message || "请求出现错误，请稍后再试",
        duration: 4
      });
    }

    /**
     * 关闭model
     */
    function close() {
      closeModal();
      reset();
    }

    /**
     * 弹窗打开前处理
     */
    async function show(loginResult) {
      if (loginResult) {
        username.value = userStore.getUserInfo.username;
        await reset();
        await bizBusiness(loginResult);
        await bizCompanyList(loginResult);
        if (!unref(isMultiBusiness) && !unref(isMultiCompany)) {
          emit("success", userStore.getUserInfo);
        } else {
          visible.value = true;
        }
      }
      //登录弹窗完成后，将登录的标识设置成false
      loginResult.isLogin = false;
      userStore.setLoginInfo(loginResult);
    }

    /**
     *重置数据
     */
    function reset() {
      companyList.value = [];
      validate_status.value = "";
      businessList.value = [];
      validate_status1.value = "";
    }

    function handleCompanyChange(e) {
      validate_status.value = "";
    }

    async function handleBusinessChange(e) {
      validate_status1.value = "";
      //根据选择的商户查询公司
      const result = await getCurrentUserCompany({ businessIds: e });
      if (!result.list || result.list.length == 0) {
        companyList.value = [];
      } else {
        companyList.value = result.list;
      }
    }

    return {
      registerModal,
      visible,
      companyList,
      isMultiCompany,
      validate_status,
      isMultiBusiness,
      businessList,
      validate_status1,
      formState,
      rules,
      layout,
      formRef,
      currTitle,
      config,
      handleCompanyChange,
      handleBusinessChange,
      show,
      handleSubmit
    };
  }
});
</script>

<style lang="less" scoped>
.loginSelectForm {
  margin-bottom: -20px;
}

.loginSelectModal {
  top: 10px;
}
</style>
